﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess.Classes;

public partial class Cart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) PopulateControls();
    }

    private void PopulateControls()
    {

        List<HangHoa> items = GioHang.Items();
        if (items.Count == 0)
        {
            // neu so product = 0 thi hien thi Empty 
            lblTitle.Text = "Shopping Cart is Empty";
            // con lai an het di 
            grid.Visible = false;
            phToolbar.Visible = false;
        }
        else
        {
            grid.DataSource = items; 
            grid.DataBind();            
            lblTotal.Text = GioHang.TotalAmount();
            
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        btnUpdate.Click += new EventHandler(btnUpdate_Click);
    }

    void btnUpdate_Click(object sender, EventArgs e)
    {
         
        int rowsCount = grid.Rows.Count; // lay tong so hang trong grid
        GridViewRow row; 

        CheckBox chbRemove; // checkbox danh dau product can xoa 

        string productId; // id cua hang hien tai 

        bool success = true;
        for (int i = 0; i < rowsCount; i++)
        {
            row = grid.Rows[i];
            // lay productid cua hang hien tai
            productId = grid.DataKeys[i].Value.ToString();
            // tim checkbox remove
            chbRemove = (CheckBox)row.FindControl("chbRemove");
            // neu checkbox da check ==> can xoa product nay
            if (chbRemove.Checked)
            {
                // tinh trang cap nhat gio hang ( thanh cong hay that bai)
                // do dung toan tu && nen chi can 1 cai fail ==> success luon luon false 
                success = success && GioHang.Remove(productId);
            }
        }
            // Hien thi thong bao
            // Khong phai tat ca viec cap nhat/xoa deu thanh cong 
            lblStatus.Text = success ? "Your shopping cart was successfully updated!" : "Some quantity updates or item removes failed! Please verify your cart!";
  
        PopulateControls();
    }
}